from fastapi.responses import JSONResponse
from fastapi import Request, FastAPI
import logging

from ..pojo.vo.Result import Result
from ..common.exception import TypeMismatchException


def register_exception_handler(app: FastAPI):
    @app.exception_handler(404)
    async def notFoundHandler(request: Request, exc):
        logging.error(f"全局异常处理器捕获到异常: {type(exc).__name__}")
        return JSONResponse(
            status_code=200,
            content=Result.error("请求地址不存在").model_dump(),
        )

    @app.exception_handler(Exception)
    async def globalExceptionHandler(request: Request, exc):
        logging.error(f"全局异常处理器捕获到异常: {type(exc).__name__}")
        return JSONResponse(
            status_code=200,
            content=Result.error("服务器内部错误, 请联系管理员").model_dump(),
        )

    @app.exception_handler(TypeMismatchException)
    async def type_not_supported_handler(request: Request, exc: TypeMismatchException):
        logging.error(
            f"""
        [TypeMismatch] 详情:
        {error_detail}
        请求路径: {request.url}
        客户端: {request.client}
        """
        )

        error_detail = {
            "expected": exc.expected_type,
            "actual": exc.actual_type,
            "context": exc.context,  # 新增字段
            "timestamp": exc.timestamp,
            "extra": exc.extra_info,
        }

        message = f"类型不匹配错误：期望 {exc._format_type(exc.expected_type)}"

        if exc.context:
            message += f"（在 {exc.context} 处）"

        return JSONResponse(
            status_code=200,
            content=Result.error(message, error_detail).model_dump(exclude_none=True),
        )

    logging.info("全局异常处理器注册成功!!!...")
